package com.dream.tihai.common.encode;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.SecureRandom;

public class DESUtil {

    private static final String fr_des = "N/X[?.\\tIgYyWbRkSpa)?y-mTB]yb>CVViBM%R\\[RiH2b`M-Ri0mTxFaCp?xF[J??.QgIhD/Xr?[?/MiCnHs";

    static {

    }

    public String charset = "utf-8";

    public static DESUtil dd;

    private DESUtil(){

    }

    public static DESUtil getInstance(){
        if (dd==null) {
            synchronized (DESUtil.class) {
                if(dd == null){
                    dd = new DESUtil();
                }
            }
        }
        return dd;
    }
    private String des(String res, String algorithm, String key, int keysize, boolean isEncode){
        try {
            KeyGenerator kg = KeyGenerator.getInstance(algorithm);
            if (keysize == 0) {
                byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
                SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
                secureRandom.setSeed(key.getBytes());
                kg.init(secureRandom);
            }else if (key==null) {
                kg.init(keysize);
            }else {
                byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
                SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
                secureRandom.setSeed(key.getBytes());
                kg.init(keysize, secureRandom);
            }
            SecretKey sk = kg.generateKey();
            SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm);
            Cipher cipher = Cipher.getInstance(algorithm);
            if (isEncode) {
                cipher.init(Cipher.ENCRYPT_MODE, sks);
                byte[] resBytes = charset==null?res.getBytes():res.getBytes(charset);
                return parseByte2HexStr(cipher.doFinal(resBytes));
            }else {
                cipher.init(Cipher.DECRYPT_MODE, sks);
                return new String(cipher.doFinal(parseHexStr2Byte(res)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
    public static final String DES = "DES";
    public int keysizeDES = 0;

    public String DESencode(String res, String key) {
        return des(res, DES, key, keysizeDES, true);
    }

    public String DESdecode(String res, String key) {
        return keyGeneratorES(res, DES, key, keysizeDES, false);
    }

    private String keyGeneratorES(String res, String algorithm, String key, int keysize, boolean isEncode){
        try {
            KeyGenerator kg = KeyGenerator.getInstance(algorithm);

            System.out.println("SecureRandom：");
            if (keysize == 0) {
                byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
                SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
                secureRandom.setSeed(key.getBytes());
                kg.init(secureRandom);
            }else if (key==null) {
                kg.init(keysize);
            }else {
                byte[] keyBytes = charset==null?key.getBytes():key.getBytes(charset);
                SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
                secureRandom.setSeed(key.getBytes());
                kg.init(keysize, secureRandom);
            }
            SecretKey sk = kg.generateKey();
            SecretKeySpec sks = new SecretKeySpec(sk.getEncoded(), algorithm);
            Cipher cipher = Cipher.getInstance(algorithm);
            if (isEncode) {
                cipher.init(Cipher.ENCRYPT_MODE, sks);
                byte[] resBytes = charset==null?res.getBytes():res.getBytes(charset);
                return parseByte2HexStr(cipher.doFinal(resBytes));
            }else {
                cipher.init(Cipher.DECRYPT_MODE, sks);
                return new String(cipher.doFinal(parseHexStr2Byte(res)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
//        String password = DESUtil.getInstance().DESencode("{\"BEG_DATE\":\"2018-06-01\",\"END_DATE\":\"2018-06-30\",\"GROUP_NODE\":\"\",\"PORT_CODE\":\"F166006,F001938\",\"SHOW_TYPE\":\"2\",\"limit\":\"5000\",\"start\":\"0\",\"GROUP_CODE\":\"\",\"schemeId\":\"578\",\"userId\":\"245\"}","N/X[?.\\tIgYyWbRkSpa)?y-mTB]yb>CVViBM%R\\[RiH2b`M-Ri0mTxFaCp?xF[J??.QgIhD/Xr?[?/MiCnHs");
//         String password = DESUtil.getInstance().DESencode("123","123456");
//
//        System.out.println(password);

//        String password = "83CFDB4D7E62E92748494651A0065D36";
//        String encoding = Encoding.getEncoding(password);
//        System.out.println(encoding);
//        System.out.println(System.getProperty("sun.jnu.encoding"));
//        System.out.println(System.getProperty("file.encoding"));
//        String s = DESUtil.getInstance().DESdecode(password, fr_des);
//        System.out.println(s);
//        System.out.println(Encoding.isWindows());
//        String s = "张三";
//        byte[] gbks = s.getBytes("GBK");
//        byte[] utf8s = s.getBytes("utf8");
//        String s1 = new String(gbks);
//        System.out.println(s1);
//        byte[] gbks1 = new String(gbks, "GBK").getBytes("UTF-8");
//        for (byte b : gbks1) {
//            System.out.println(b);
//        }
//        System.out.println(gbks1);
//        System.out.println(utf8s);
//        for (byte utf8 : utf8s) {
//            System.out.println(utf8);
//        }
    }
}
